/**
 * 管理系统视图路由模块
 */
const express = require('express')
const router = express.Router()

/**
 * 引入其他模块
 */
const db = require('../utils/db')
const moment = require('moment')

router.get('/admin', (req, res) => {
  res.render('admin/index.html')
})
router.get('/admin/categories', (req, res) => {
  res.render('admin/categories.html')
})
router.get('/admin/comments', (req, res) => {
  res.render('admin/comments.html')
})
router.get('/admin/login', (req, res) => {
  res.render('admin/login.html')
})
router.get('/admin/nav-menus', (req, res) => {
  res.render('admin/nav-menus.html')
})
router.get('/admin/password-reset', (req, res) => {
  res.render('admin/password-reset.html')
})
router.get('/admin/post-add', (req, res) => {
  res.render('admin/post-add.html')
})
router.get('/admin/post-edit', (req, res, next) => {
  // const sql = 'SELECT * FROM ali_article LEFT JOIN ali_cate ON article_cateid = cate_id WHERE article_id = ?'
  const sql = 'SELECT * FROM ali_article WHERE article_id = ?'
  db.query(sql, req.query.id, (err, result) => {
    if (err) return next(err)
    const sql2 = 'select * from ali_cate'
    db.query(sql2, (error, ret) => {
      if (error) return next(error)
      res.render('admin/post-edit.html', {
        article: result[0],
        categories: ret
      })
    })
  })
})
router.get('/admin/posts', (req, res, next) => {
  const sql = `
    select admin_id, admin_nickname, article_id, article_title, article_adminid, article_cateid, article_addtime, article_status, cate_name
    from ali_admin a
    inner join ali_article b
    on a.admin_id = b.article_adminid
    left join ali_cate c
    on b.article_cateid = c.cate_id
  `
  db.query(sql, (err, result) => {
    // throw err 会抛出异常，退出程序
    if (err) return next(err)
    console.log('result---', result)
    const resList = JSON.parse(JSON.stringify(result)).map(item => {
      return {
        article_id: item.article_id,
        article_title: item.article_title,
        admin_nickname: item.admin_nickname,
        cate_name: item.cate_name,
        article_addtime: moment(item.article_addtime).format('YYYY-MM-DD'),
        article_status: item.article_status
      }
    })
    res.render('admin/posts.html', {list: resList})
  })
})
router.get('/admin/profile', (req, res) => {
  res.render('admin/profile.html')
})
router.get('/admin/settings', (req, res) => {
  res.render('admin/settings.html')
})
router.get('/admin/slides', (req, res) => {
  res.render('admin/slides.html')
})
router.get('/admin/users', (req, res) => {
  res.render('admin/users.html')
})

module.exports = router